<template>
  <div class="row">
    <div class="col-12 text-subtitle1 text-center">修改密码</div>
    <q-banner inline-actions rounded class="col-12 text-white bg-red q-mt-sm" v-if="serverErrorMessage">
      {{serverErrorMessage}}
      <template v-slot:action>
        <q-btn flat icon="close" size="sm" dense @click="serverErrorMessage=null" />
      </template>
    </q-banner>
    <q-input class="col-12 q-mt-md" v-model="form.oldPassword" placeholder="旧密码" type="password" outlined square dense
      autofocus :disable="workingState" :error="v$.oldPassword.$error" :error-message="e$(v$.oldPassword.$errors)"
      no-error-icon :hide-bottom-space="true">
      <template v-slot:append>
        <q-icon color="grey-5" name="vpn_key" />
      </template>
    </q-input>
    <q-input class="col-12 q-mt-md" v-model="form.newPassword" placeholder="新密码" type="password" outlined square dense
      :disable="workingState" :error="v$.newPassword.$error" :error-message="e$(v$.newPassword.$errors)" no-error-icon
      :hide-bottom-space="true">
      <template v-slot:append>
        <q-icon color="primary" name="vpn_key" />
      </template>
    </q-input>
    <q-input class="col-12 q-mt-md" v-model="form.repeatNewPassword" placeholder="再次确认新密码" type="password" outlined
      square
      dense :disable="workingState" :error="v$.repeatNewPassword.$error"
      :error-message="e$(v$.repeatNewPassword.$errors)" no-error-icon :hide-bottom-space="true">
      <template v-slot:append>
        <q-icon color="primary" name="vpn_key" />
      </template>
    </q-input>
    <q-btn class="q-mt-md col-12" color="primary" label="确定" :loading="workingState" @click="confirm">
      <template v-slot:loading>
        <q-spinner class="on-left" />
        提交中...
      </template>
    </q-btn>
    <q-btn class="q-mt-sm col-12" color="primary" outline label="返回" :disable="workingState" @click="fx.router.go(-1)" />
  </div>
</template>

<script lang="ts">
export default {
  name: 'changePasswordStd',
}
</script>

<script lang="ts" setup>
import {reactive, ref, onBeforeMount, computed} from 'vue'
import useVuelidate from '@vuelidate/core'
import {UserAuth} from '../../defs/comm'
import {useJsencryptHelper} from '../../hooks/jsencryptHelper'

const serverErrorMessage = ref('')
const workingState = ref(false)
const e$ = $f.getFieldErrStr

const reurl = ref('')

//属性
const props = defineProps({
  useStrictPassword: {
    type: Boolean,
    default: false,
  },
  useExtraPasswordCheck:{
    type: Boolean,
    default: false,
  }
})

//表单
const form = reactive({
  oldPassword: '',
  newPassword: '',
  repeatNewPassword: '',
})

//表单验证
const rules = {
  oldPassword: {
    required: $f.validators.required,
    password: $f.validators.password,
  },
  newPassword: {
    required: $f.validators.required,
    password: props.useStrictPassword ? $f.validators.strictPassword : $f.validators.password,
    extraPasswordRepeatCheck:(props.useStrictPassword && props.useExtraPasswordCheck)?$f.validators.extraPasswordRepeatCheck:''
  },
  repeatNewPassword: {
    required: $f.validators.required,
    password: props.useStrictPassword ? $f.validators.strictPassword : $f.validators.password,
    passwordConfirm: $f.validators.passwordConfirm(computed(() => form.newPassword)),
    extraPasswordRepeatCheck:(props.useStrictPassword && props.useExtraPasswordCheck)?$f.validators.extraPasswordRepeatCheck:''
  },
}

const v$ = useVuelidate(rules, form, {$autoDirty: true})
const encPassword = useJsencryptHelper()

const confirm = function () {
  v$.value
    .$validate()
    .then((valRes) => {
      if (valRes) {
        workingState.value = true
        serverErrorMessage.value = ''
        let changePasswordModel
        if ($f.globalCfg.encTransPwd) {
          changePasswordModel = {
            useEncryptPwd: true,
            encryptedOldPwd: encPassword(form.oldPassword),
            encryptedNewPwd: encPassword(form.newPassword),
          }
        } else {
          changePasswordModel = {oldPassword: form.oldPassword, newPassword: form.newPassword}
        }
        $f.axios
          .post<UserAuth>('/comm/auth/change-password', changePasswordModel)
          .then((resp) => {
            // 修改密码AppToken会发生变化，这意味着用户得重新登录，但这样对用户而言不友好，这两个动作就相当于帮助用户重新登录了
            $f.ua!.value = resp.data
            localStorage.setItem('ua', JSON.stringify(resp.data))
            $f.router.push(reurl.value).catch(() => {
              //ignore
            })
          })
          .catch((err) => {
            serverErrorMessage.value = $f.getAxiosErrMsg(err)
            workingState.value = false
          })
      }
    })
    .catch(() => {
      //ignore
    })
}

onBeforeMount(() => {
  reurl.value = $f.router.currentRoute.value.query.reurl as string
  if (!reurl.value) {
    reurl.value = '/'
  }
})

const fx = $f
</script>
